package com.dudy.web.user;

import com.dudy.util.UserUtil;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author <a href="mailto:wb-zhaojunwei@alibaba-inc.com">wb-zhaojunwei></a>
 * @version 1.0
 * @Description 类说明
 * @since 2016/3/10
 */
@Controller
@RequestMapping(value = "user")
public class UserController {
    @Resource
    private IdentityService identityService;

    @RequestMapping(value = "logon")
    public String logon(@RequestParam(value = "username") String username, @RequestParam(value = "password") String pwd, HttpSession session) {
        //判断密码是否对给定用户有效，判断用户、密码是否为null
        boolean result = identityService.checkPassword(username, pwd);
        if (result) {
//            根据用户查询用户信息
            User user = identityService.createUserQuery().userId(username).singleResult();
            UserUtil.saveUserToSession(session, user);
            //查询该用户所属于的组，可能身兼数职
            List<Group> groups = identityService.createGroupQuery().groupMember(user.getId()).list();
            session.setAttribute("groups", groups);
            String[] groupNames = new String[groups.size()];
            for (int i = 0; i < groupNames.length; i++) {
                groupNames[i] = groups.get(i).getName();
            }
            session.setAttribute("groupNames", groupNames);
            return "redirect:/main/index";
        } else {
            return "redirect:/login?error=true";
        }
    }

    @RequestMapping(value = "logout")
    public String logout(HttpSession session) {
        session.removeAttribute(UserUtil.USER);
        return "/login";
    }

}
